import { useContext, useLayoutEffect } from 'react';
import ReactReduxContext from '../components/Context';
import useForceUpdate from './useForceUpdate';

export default function useSelector(selector) {
  const store = useContext(ReactReduxContext);

  const forceUpdate = useForceUpdate();
  useLayoutEffect(() => {
    const unsubscribe = store.subscribe(() => {
      forceUpdate();
    });
    return () => {
      unsubscribe && unsubscribe();
    };
  }, [store]);

  return selector(store.getState());
}
